package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {


        //1.包含用户名和密码
        if (dto.getPhone() != null && dto.getPassword() != null){
            //数据库查询
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,dto.getPhone()));
            //用户不存在
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //用户存在
            String salt = apUser.getSalt();
            String pwd = dto.getPassword();
            pwd = DigestUtils.md5DigestAsHex((pwd + salt).getBytes());
            if (!pwd.equals(apUser.getPassword())){
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //用户存在,返回数据
            Map<String,Object> result =  new HashMap<>();
            result.put("token",AppJwtUtil.getToken((long)apUser.getId()));
            apUser.setPassword("");
            apUser.setSalt("");
            result.put("user",apUser);
            return ResponseResult.okResult(result);
        }else {
            //2.不包含用户名和密码,游客登录
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> result = new HashMap<>();
            result.put("token",token);
            return ResponseResult.okResult(result);
        }
    }
}













